//
//  YCTitleView.swift
//  weiBoSwift
//
//  Created by 刘胤辰 on 16/7/24.
//  Copyright © 2016年 it.com. All rights reserved.
//

import UIKit

class YCTitleView: UIView ,UITextFieldDelegate{

    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0,UIScreen.mainScreen().bounds.size.width, 35))
        
        //添加
        addSubview(searchBtn)
        addSubview(textField)
        //设置约束
        textField.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.bottom.equalTo(self)
            make.trailing.equalTo(self)
        }
        searchBtn.snp_makeConstraints { (make) -> Void in
            
            //此处记住，在update约束的时候要记着一定要分开写
//            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
//            这样写出问题了，更改不了约束
            make.trailing.top.bottom.equalTo(self)
            make.width.equalTo(60)
        }
    }
    
    // MARK: -- 懒加载
    lazy var textField:UITextField = {
        let text=UITextField()
        
        let img = UIImageView(imageName: "searchbar_textfield_search_icon")
        img.contentMode = .Center
        img.frame.size = CGSize(width: 35, height: 35)
        
        text.backgroundColor=UIColor.whiteColor()
        text.placeholder="我是卖报的小当家"
        text.layer.borderColor = UIColor.orangeColor().CGColor
        text.layer.borderWidth = 2
        text.layer.cornerRadius = 5
        text.layer.masksToBounds = true
        text.leftView=img
        text.leftViewMode = .Always
        
        text.delegate=self
        
        return text
    }()
    lazy var searchBtn:UIButton = {
        let btn = UIButton(title: "取消", titleColor: UIColor.darkGrayColor(), font: 16)
        btn.backgroundColor = UIColor.greenColor()
        btn.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        
        return btn
    }()
    
    @objc private func click(){
        
        textField.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self)
        }
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            self.layoutIfNeeded()
            
            }) { (_) -> Void in
                
                self.textField.resignFirstResponder()
        }
    }
    
    //代理方法
    func textFieldDidBeginEditing(textField: UITextField) {
        
        
        self.textField.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self).offset(-50)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
